package top.starmc.starpet.listener

import eos.moe.dragoncore.api.event.KeyPressEvent
import eos.moe.dragoncore.api.gui.event.CustomPacketEvent
import eos.moe.dragoncore.network.PacketSender
import org.bukkit.entity.Player
import org.bukkit.event.entity.EntityDamageByEntityEvent
import org.bukkit.event.entity.EntityDamageEvent
import org.bukkit.event.player.PlayerChangedWorldEvent
import org.bukkit.event.player.PlayerJoinEvent
import org.bukkit.event.player.PlayerQuitEvent
import taboolib.common.platform.event.SubscribeEvent
import taboolib.module.lang.event.PlayerSelectLocaleEvent
import taboolib.module.lang.event.SystemSelectLocaleEvent
import top.starmc.starpet.config.Config
import top.starmc.starpet.util.getPlayerData
import top.starmc.starpet.util.loadPlayerData

object Players {
    @SubscribeEvent
    fun onJoin(event: PlayerJoinEvent) {
        event.player.loadPlayerData()
    }

    @SubscribeEvent
    fun onQuit(event: PlayerQuitEvent) {
        event.player.getPlayerData().saveData()
    }

    @SubscribeEvent
    fun onKeyPress(event: KeyPressEvent) {
        with(event.player.getPlayerData()) {
            if (internal != null) {
                if (event.key == Config.callKey) {
                    callPet()
                }
                runSkill("key", event.keys)
            }
        }
    }

    @SubscribeEvent
    fun onChangeWorld(event: PlayerChangedWorldEvent) {
        with(event.player.getPlayerData()) {
            entity?.let {
                removeEntity()
                spawnEntity()
            }
        }
    }

    @SubscribeEvent
    fun onHurt(event: EntityDamageEvent) {
        if (event.entity is Player) {
            with((event.entity as Player).getPlayerData()) {
                if (internal != null) {
                    runSkill("hurt")
                }
            }
        }
    }

    @SubscribeEvent
    fun onAttack(event: EntityDamageByEntityEvent) {
        if (event.damager is Player) {
            with((event.damager as Player).getPlayerData()) {
                if (internal != null) {
                    runSkill("attack")
                }
            }
        }
    }

    @SubscribeEvent
    fun requestUpdate(event: CustomPacketEvent) {
        if (event.identifier == "StarPet_UpdateItem") {
            with(event.player) {
                PacketSender.putClientSlotItem(this, Config.equipSlot, getPlayerData().item)
            }
        }
    }

    @SubscribeEvent
    fun playerLang(event: PlayerSelectLocaleEvent) {
        event.locale = "zh_CN"
    }

    @SubscribeEvent
    fun systemLang(event: SystemSelectLocaleEvent) {
        event.locale = "zh_CN"
    }
}